<template>
  <div class="vue-shop-show ts-shop-container">
    <!-- 主图片显示区域 -->
    <div class="ts-img-s">
      <a href="#" @click.prevent="showZoom">
        <img 
          :src="currentImage" 
          :alt="product.name"
          class="main-image"
          @load="onImageLoad"
          @error="onImageError"
        />
      </a>
    </div>
    
    <!-- 缩略图容器 -->
    <div class="ts-pic-container" v-if="images.length > 1">
      <!-- 左箭头 -->
      <button 
        class="ts-img-s-arr-l nav-arrow" 
        @click="scrollLeft"
        :disabled="scrollPosition <= 0"
      >
        ‹
      </button>
      
      <!-- 右箭头 -->
      <button 
        class="ts-img-s-arr-r nav-arrow" 
        @click="scrollRight"
        :disabled="scrollPosition >= maxScrollPosition"
      >
        ›
      </button>
      
      <!-- 缩略图滚动容器 -->
      <div class="ts-img-s-con">
        <ul 
          class="thumbnail-list"
          :style="{ transform: `translateX(-${scrollPosition * 90}px)` }"
        >
          <li 
            v-for="(image, index) in images" 
            :key="index"
            class="thumbnail-item"
            :class="{ 'ts-select-img': index === currentIndex }"
            @click="selectImage(index)"
          >
            <img 
              :src="image.thumb || image.url" 
              :alt="`${product.name} ${index + 1}`"
            />
          </li>
        </ul>
      </div>
    </div>
    
    <!-- 放大镜遮罩（可选） -->
    <div 
      v-if="showMagnifier" 
      class="magnifier-overlay"
      @mousemove="updateMagnifier"
      @mouseleave="hideMagnifier"
    >
      <div 
        class="magnifier-lens"
        :style="magnifierStyle"
      ></div>
      <div class="magnified-image">
        <img 
          :src="currentImage"
          :style="magnifiedImageStyle"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ProductImageViewer',
  props: {
    product: {
      type: Object,
      required: true,
      default: () => ({
        name: '',
        images: []
      })
    },
    enableMagnifier: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      currentIndex: 0,
      scrollPosition: 0,
      showMagnifier: false,
      magnifierX: 0,
      magnifierY: 0,
      imageLoaded: false
    }
  },
  computed: {
    images() {
      return this.product.images || []
    },
    currentImage() {
      return this.images[this.currentIndex]?.url || ''
    },
    maxScrollPosition() {
      const containerWidth = 354 // 392 - 18*2 - 2px for arrows
      const itemWidth = 90
      const visibleItems = Math.floor(containerWidth / itemWidth)
      return Math.max(0, this.images.length - visibleItems)
    },
    magnifierStyle() {
      return {
        left: `${this.magnifierX - 50}px`,
        top: `${this.magnifierY - 50}px`,
        display: this.showMagnifier ? 'block' : 'none'
      }
    },
    magnifiedImageStyle() {
      return {
        transform: `translate(-${this.magnifierX * 2}px, -${this.magnifierY * 2}px) scale(2)`
      }
    }
  },
  methods: {
    selectImage(index) {
      this.currentIndex = index
      this.$emit('image-change', this.images[index])
    },
    scrollLeft() {
      if (this.scrollPosition > 0) {
        this.scrollPosition--
      }
    },
    scrollRight() {
      if (this.scrollPosition < this.maxScrollPosition) {
        this.scrollPosition++
      }
    },
    showZoom() {
      if (this.enableMagnifier) {
        this.showMagnifier = true
      }
      this.$emit('zoom-click', this.currentImage)
    },
    updateMagnifier(event) {
      if (!this.enableMagnifier) return
      
      const rect = event.currentTarget.getBoundingClientRect()
      this.magnifierX = event.clientX - rect.left
      this.magnifierY = event.clientY - rect.top
    },
    hideMagnifier() {
      this.showMagnifier = false
    },
    onImageLoad() {
      this.imageLoaded = true
      this.$emit('image-loaded')
    },
    onImageError() {
      console.error('图片加载失败:', this.currentImage)
      this.$emit('image-error', this.currentImage)
    },
    // 键盘导航
    handleKeyboard(event) {
      switch(event.key) {
        case 'ArrowLeft':
          if (this.currentIndex > 0) {
            this.selectImage(this.currentIndex - 1)
          }
          break
        case 'ArrowRight':
          if (this.currentIndex < this.images.length - 1) {
            this.selectImage(this.currentIndex + 1)
          }
          break
      }
    }
  },
  mounted() {
    if (this.enableMagnifier) {
      document.addEventListener('keydown', this.handleKeyboard)
    }
  },
  beforeUnmount() {
    if (this.enableMagnifier) {
      document.removeEventListener('keydown', this.handleKeyboard)
    }
    
    // 清理可能的定时器
    if (this.magnifierTimer) {
      clearTimeout(this.magnifierTimer)
      this.magnifierTimer = null
    }
    
    // 清理可能的事件监听器
    if (this.$el && this.$el.parentNode) {
      // 移除所有事件监听器
      const clone = this.$el.cloneNode(true)
      this.$el.parentNode.replaceChild(clone, this.$el)
    }
    
    // 清理组件引用
    this.$el = null
  },
  watch: {
    'product.images': {
      handler() {
        this.currentIndex = 0
        this.scrollPosition = 0
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
.magnifier-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  cursor: zoom-in;
}

.magnifier-lens {
  position: absolute;
  width: 100px;
  height: 100px;
  border: 1px solid #ccc;
  background: rgba(255, 255, 255, 0.3);
  pointer-events: none;
}

.magnified-image {
  position: absolute;
  top: 0;
  right: -400px;
  width: 400px;
  height: 400px;
  border: 1px solid #ccc;
  background: white;
  overflow: hidden;
  z-index: 1000;
}

.magnified-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 800px;
  height: 800px;
}

.nav-arrow:focus {
  outline: 2px solid #ff4e00;
  outline-offset: 2px;
}

.thumbnail-item {
  position: relative;
}

.thumbnail-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 78, 0, 0.1);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.thumbnail-item:hover::before {
  opacity: 1;
}

@media (max-width: 768px) {
  .ts-shop-container {
    width: 100%;
    height: auto;
  }
  
  .magnified-image {
    right: -300px;
    width: 300px;
    height: 300px;
  }
  
  .magnified-image img {
    width: 600px;
    height: 600px;
  }
}
</style>